package tws

import (
	"context"
	"go-web-scaffold/config"
	"log"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

type GinServer struct {
	engine *gin.Engine
	server *http.Server
}

func CreateServer(cfg *config.GlobalConfig) *GinServer {
	engine := gin.Default()
	serv := &http.Server{
		Addr:           ":" + cfg.Addr,
		Handler:        engine,
		ReadTimeout:    time.Duration(cfg.ReadTimeout) * time.Second,
		WriteTimeout:   time.Duration(cfg.WriteTimeout) * time.Second,
		MaxHeaderBytes: 1 << uint(cfg.MaxHeaderBytes),
	}
	return &GinServer{
		engine: engine,
		server: serv,
	}
}

func (_this *GinServer) NotFound(callback func(ctx *gin.Context)) {
	if callback == nil {
		log.Fatal("callback is invalid")
		return
	}
	_this.engine.NoRoute(func(ctx *gin.Context) {
		callback(ctx)
	})
}

func (_this *GinServer) Start(callback func(engine *gin.Engine)) {
	if callback == nil {
		log.Fatal("callback is nil")
		return
	}
	callback(_this.engine)
	log.Println(" http server has started")
	if error := _this.server.ListenAndServe(); error != nil {
		log.Panic("server start error")
	}

}
func (_this *GinServer) Stop() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if error := _this.server.Shutdown(ctx); error != nil {
		log.Panic(error.Error())
	}
	log.Println(" http server has stopped")
}
